#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include "Log.hpp"
#include "Thread.hpp"
#include "Cond.hpp"
#include "Mutex.hpp"

// .hpp header only

namespace ThreadPoolModule
{
    using namespace ThreadModlue;
    using namespace LogModule;
    using namespace CondModule;
    using namespace MutexModule;

    static const int gnum = 5;
    template <typename T>
    class ThreadPool
    {
    private:
        void WakeUpAllThreads()
        {
            LockGuard lockguard(_lock);
            if(_sleepnum) 
            {
                //休眠线程不为0
                _cond.BroadCast();
            }
            LOG(LogLevel::INFO) << "唤醒所以休眠线程";
        }
        void WakeUpOne()
        {
            _cond.Signal();
            LOG(LogLevel::INFO) << "唤醒一个休眠线程";
        }
        void Start()
        {
            if(_isrunning)
            {
                return;
            }
            _isrunning = true;
            for(auto &thread : _threads)
            {
                //创建线程
                thread.start();
                LOG(LogLevel::INFO) << "start new thread success: " << thread.Id();
            }
        }
        ThreadPool(int num = gnum) : _num(num), _isrunning(false), _sleepernum(0)
        {
            for (int i = 0; i < num; i++)
            {
                _threads.emplace_back(
                    [this]()
                    {
                        HandlerTask();
                    });
            }
        }
        //禁止除了获取单例以外的任何方法创建实例
        ThreadPool(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

    public:
        static ThreadPool<T>* GetInstance()
        {
            if(inc == nullptr)
            {
                //加锁
                LockGuard lockguard(_lock);

                LOG(LogLevel::DEBUG) << "获取单例....";
                if(inc == nullptr)
                {
                    LOG(LogLevel::DEBUG) << "首次使用单例，创建...";
                    inc = new ThreadPool<T>();
                    inc -> Start();
                }
            }
            return inc;
        }

        void Stop()
        {
            if(!_isrunning)
            {
                return;
            }
            _isrunning = false;//停止运行

            //唤醒所以线程,唤醒所有阻塞线程，确保它们能及时响应信号并终止，从而安全、彻底地停止线程池的运行。
            //这一过程避免了线程泄漏，保证了线程池资源的正确回收
            WakeUpAllThreads();
        }
        void Join()
        {
            for(auto& thread : _threads)
            {
                thread.join();
            }
        }
        void HandleTask()
        {
            char name[128];
            pthread_getname_np(_tid, name, sizeof(name));
            while(true)
            {
                T t;
                {
                    LockGuard lockguard(_lock);
                    //1.队列为空/线程池没有退出
                    while(_taskq.empty() && _isrunning)
                    {
                        _sleepnum++;
                        _cond.Wait();
                        _sleepnum--;
                    }
                    //2.内部线程被唤醒
                    if(!_isrunning && _taskq.empty())
                    {
                        LOG(LogLevel::INFO) << name << " 退出了, 线程池退出&&任务队列为空";
                        break;
                    }

                    //此时一定有任务
                    t = _taskq.front();
                    _taskq.pop();
                }
                t();//执行任务
            }
        }

        bool Enqueue(const T& in)
        {
            if(_isrunning)
            {
                LockGuard lockguard(_mutex);
                _taskq.push(in);
                if(_threads.size() == _sleepnum)
                {
                    WakeUpOne();
                }
                return true;
            }
            return false;
        }

        ~Thread()
        {}
    private:
        std::vector<Thread> _threads;//线程池的具体容器
        int _num;//线程池中线程的个数
        std::queue<T> _taskq;//任务队列
        Cond _cond;//进程信号控制工具
        Mutex _mutex;//锁
        bool _isrunning;
        int _sleepnum;//休眠的线程数量

        static ThreadPool<T>* inc;//单例指针
        static Mutex _lock;//static 成员，确保所有线程共享同一把锁，否则无法实现同步。
    };

    //对静态的类私有成员变量的初始化(::)
    template <typename T>
    ThreadPool<T> *ThreadPool<T>::inc = nullptr;

    template <typename T>
    Mutex ThreadPool<T>::_lock;
}
